package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.personal.PersonAddReceiveAddressActivity;
import cn.didi.feidi.androidorder.adapter.PersonReceiverAddressListViewAdapter;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.assembly.DeleteGoodsFragmentDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.db.UserAddressDao;
import cn.didi.feidi.androidorder.fragment.ConfirmOrderFragment;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.UserAddress;


public class PersonReceiveAddressFragment extends FeidiBaseFragment {

    public static final int SOURCE = 2; //来源是 确认订单  ConfirmOrderFragment
    private static final String TAG = "PersonReceiveAddress";
    private static final int REQUEST_CODE = 2;
    private static final int ADD_ADDRESS_RESULT_CODE = 3;
    private static final int EDIT_ADDRESS_RESULT_CODE = 4;
    PersonReceiverAddressListViewAdapter adapter;
    AsyncSession asyncSession;
    private List<UserAddress> mUserAddresses = new ArrayList<>();
    private LinearLayout personAddReceiveMessage;
    private ListView personReceiveMessageListView;
    private LinearLayout placeHolderLl;
    private int source;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonReceiveAddressFragment newInstance(Bundle bundle) {
        PersonReceiveAddressFragment fragment = new PersonReceiveAddressFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_receive_address, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        personReceiveMessageListView = (ListView) rootView.findViewById(R.id.person_receive_message_list_view);
        personAddReceiveMessage = (LinearLayout) rootView.findViewById(R.id.person_receive_add_receive_message);
        placeHolderLl = (LinearLayout) rootView.findViewById(R.id.address_place_holder);

        source = getActivity().getIntent().getIntExtra("source", -1);

        //来源是 ConfirmOrderFragment 不需要显示管理的按钮
        if (source == SOURCE) {
            getFeidiActionBar().getSettingView().setVisibility(View.GONE);
        }


    }

    @Override
    protected void initData() {


        adapter = new
                PersonReceiverAddressListViewAdapter(getContext(), R.layout.item_person_receive_address, mUserAddresses);
        personReceiveMessageListView.setAdapter(adapter);

        asyncSession = OrderApplication.getDaoSession().startAsyncSession();

        //需要向后台拿地址
        if (UserManager.getNeedRequestAddress()) {
            Log.d(TAG, "initData:  server");
            getAddressFromNetwork();
        } else {
            Log.d(TAG, "initData: local");
            //本地数据库有数据
            getAddressFromLocalDb();
        }


    }

    private void getAddressFromLocalDb() {

        asyncSession.setListenerMainThread(new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {

                if (operation.isFailed()) {
                    Toast.makeText(mActivity, "获取数据错误", Toast.LENGTH_SHORT).show();
                }

                if (operation.getType() == AsyncOperation.OperationType.QueryList) {
                    List<UserAddress> data = (List<UserAddress>) operation.getResult();

                    mUserAddresses.clear();
                    mUserAddresses.addAll(data);

//                    Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
//                    Log.d(TAG, "onSuccess: " + gson.toJson(data));
//                    adapter.clear();
//                    adapter.addAll(data);
                    adapter.notifyDataSetChanged();

                    if (adapter.getCount() == 0) {
                        placeHolderLl.setVisibility(View.VISIBLE);
                    } else {
                        placeHolderLl.setVisibility(View.GONE);
                    }
//                    adapter.notifyDataSetChanged();
                }


            }
        });

        asyncSession.queryList(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(UserAddress.class))
                .where(UserAddressDao.Properties.UserId.eq(UserManager.getUserId()))
                .build());

    }

    private void getAddressFromNetwork() {
//           2017/8/23 后期换回 真实 id token ---jinXiong
        HashMap<String, String> parameters = new HashMap<>();
//        parameters.put("userId", Constants.USER_ID);
        parameters.put("userId", UserManager.getUserId());

//        parameters.put("token", Constants.TOKEN);
        parameters.put("token", UserManager.getToken());

        executeRequest(new AppActionRequest<>(Api.GET_USER_ADDRESS, parameters, new TypeToken<ApiResponse<List<UserAddress>>>() {
        }.getType(), new ActionCallbackListener<List<UserAddress>>() {
            @Override
            public void onSuccess(String message, List<UserAddress> data) {

                mUserAddresses.clear();
                mUserAddresses.addAll(data);

                adapter.notifyDataSetChanged();

                if (adapter.getCount() == 0) {
                    placeHolderLl.setVisibility(View.VISIBLE);
                } else {
                    placeHolderLl.setVisibility(View.GONE);
                }


                for (int i = 0; i < data.size(); i++) {
                    Log.d(TAG, "onSuccess: " + data.get(i).getDefaultAddress());
                    asyncSession.insert(data.get(i));
                }

                UserManager.setNeedRequestAddress("1");

            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Toast.makeText(mActivity, "获取地址失败", Toast.LENGTH_SHORT).show();
            }
        }));
    }

    @Override
    protected void addListener() {


        adapter.setCallback(new PersonReceiverAddressListViewAdapter.Callback() {

            /**
             * 删除地址回调
             *
             * @param userAddress
             */
            @Override
            public void deleteCallback(final UserAddress userAddress) {

                final DeleteGoodsFragmentDialog dialog = new DeleteGoodsFragmentDialog();
                dialog.setTitle("删除此地址");
                dialog.setLeftMessage("删除");
                dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, String> parameters = new HashMap<>();

                        //parameters.put("userId", Constants.USER_ID);
                        parameters.put("userId", UserManager.getUserId());
                        //parameters.put("token", Constants.TOKEN);
                        parameters.put("token", UserManager.getToken());

                        parameters.put("userAddressId", userAddress.getUserAddressId());

                        executeRequest(new AppActionRequest<>(Api.DELETE_USER_ADDRESS, parameters, new TypeToken<ApiResponse<Object>>() {
                        }.getType(), new ActionCallbackListener<Object>() {
                            @Override
                            public void onSuccess(String message, Object data) {
                                Log.d(TAG, "onSuccess:  success delete");
                                dialog.dismiss();
                                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                    @Override
                                    public void onAsyncOperationCompleted(AsyncOperation operation) {
                                        if (operation.isFailed()) {
                                            return;
                                        }
                                        mUserAddresses.remove(operation.getParameter());
//
                                        adapter.notifyDataSetChanged();

                                        if (adapter.getCount() == 0) {
                                            placeHolderLl.setVisibility(View.VISIBLE);
                                        } else {
                                            placeHolderLl.setVisibility(View.GONE);
                                        }
                                    }
                                });

                                //数据库删除
                                asyncSession.delete(userAddress);
                            }

                            @Override
                            public void onFailure(int errorEvent, String message) {
                                Log.d(TAG, "onFailure: delete failure");
                                dialog.dismiss();

                            }
                        }));


                    }
                });
                dialog.show(getChildFragmentManager(), "delete");

            }

            @Override
            public void editCallback(UserAddress userAddress) {
                Intent intent = new Intent(getActivity(), PersonAddReceiveAddressActivity.class);
                intent.putExtra("userAddress", userAddress);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });


        personReceiveMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //来源是  ConfirmOrderFragment
                if (source == SOURCE) {
                    Activity activity = PersonReceiveAddressFragment.this.getActivity();
                    Intent intent = new Intent();
                    intent.putExtra("userAddress", mUserAddresses.get(position));
                    activity.setResult(ConfirmOrderFragment.RESULT_CODE, intent);
                    activity.finish();
                    return;
                }

                Log.d(TAG, "onItemClick: " + parent.getClass().getSimpleName());
                Log.d(TAG, "onItemClick: " + view.getClass().getSimpleName());


            }
        });

        personAddReceiveMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonAddReceiveAddressActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        getFeidiActionBar().getSettingView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (adapter.isShowManager()) {
                    adapter.setShowManager(false);
                    getFeidiActionBar().setSettingText("管理");
                } else {
                    adapter.setShowManager(true);
                    getFeidiActionBar().setSettingText("完成");
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            getAddressFromLocalDb();
        }

    }


}
